<?php
namespace Controllers;

class projectController extends Controller
{
    // 采用两层循环n^2除去重复的
    public function tableMerge($res)
    {
        $count = count($res);
        for ($i = 0; $i < $count; $i++) 
        { 
            for ($j = $i + 1; $j < $count; $j++) 
            { 
                if(@$res[$i]['table_id'] === @$res[$j]['table_id']) 
                {
                        
                    unset($res[$j]);
                }
            }
        }
        return $res;
    }
    
    public function checkRecord($user_id, $table_id, $action)
    {
        $this->container['db']->insert($this->checkTable, [
            'user_id' => $user_id,
            'table_id' => $table_id,
            'action' => $action,
            'time' => time()
        ]);
        return ($this->container['db'])?true:false;
    }

    public function projectList($request, $respond, $args)
    {
        $this->checkAccess($this->getUserId(), '12345');
        // 取出数据库中该用户的项目
        $id = $this->getUserId();
        $res = $this->container['db']->select($this->projectTable, '*', [
            'user_id' => $id
        ]);
        if($this->container['db']->error()[1]) return self::jsonFail('数据库错误');
        // 非项目管理员的项目列表
        $res1 = $this->container['db']->select($this->roleProjectTable, 'project_id', [
            'user_id' => $id
        ]);
        if($this->container['db']->error()[1]) return self::jsonFail('数据库错误');
        if($res1)
        {
            foreach ($res1 as $key => $project_id) 
            {
                $table = $this->container['db']->select($this->projectTable, '*', [
                    'project_id' => $project_id
                ]);
                if($table) array_push($res, $table[0]);
                if($this->container['db']->error()[1]) return self::jsonFail('数据库错误');
            }
        }
        return json_encode($res);
    }

    public function projectAdd()
    {
        $this->checkAccess($this->getUserId(), '1');        
        $userId = $this->getUserId();
        $data = $this->container['db']->insert($this->projectTable, [
            'project_id' => '',
            'name' =>  $_POST['name'],
            'money' => $_POST['money'],
            'summary' => $_POST['summary'],
            'leader' => $_POST['leader'],
            'leader_phone' => $_POST['leader_phone'],
            'teacher' => $_POST['teacher'],
            'teacher_phone' => $_POST['teacher_phone'],
            'user_id' => $userId,
            'balance' => $_POST['money']
        ]);
        if(!$this->container['db']->error()[1])
        {
            return self::jsonSuccess("增加成功");
        }
        else
        {
            return self::jsonFail("增加失败");
        }
    }

    // 未改： 增加非项目管理员的申购表列表
    public function tablesList()
    {
        $this->checkAccess($this->getUserId(), '12345');        
        $userId = $this->getUserId();
        $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
            '[><]'.$this->projectTable.'(project)' => 'project_id'
        ], [
            'role.table_id',
            'role.sum_money',
            'role.man_phone',
            'role.expense',
            'role.dep_audit',
            'role.center_audit',
            'role.status',
            'role.comment',
            'project.name'
        ], [
            'project.user_id' => $userId
        ]);
        if(!$this->container['db']->error()[1])
        {
            return json_encode($res);
        }
        else
        {
            return self::jsonFail('获取失败');
        }
    }

    /**
     *    emmmm用于做申购表时间轴的接口
     */
    public function pTablesList()
    {
        $this->checkAccess($this->getUserId(), '12345');        
        $id = $_GET['id'];
        $userId = $this->getUserId();
        if($id)
        {
            $merges_id = $this->container['db']->select($this->roleApplyTable, 'merge_id', [
                'merge_id[!]' => 0,
                'project_id' => $id
            ]);
            // $merges_id = json_encode($merges_id);
            $res = array();
            // 返回项目管理员所管理的项目的所有申购表
            if($merges_id)
            {
                $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
                    '[><]'.$this->projectTable.'(project)' => 'project_id'
                ], [
                    'role.table_id',
                    'role.sum_money',
                    'role.man_phone',
                    'role.expense',
                    'role.dep_audit',
                    'role.center_audit',
                    'role.status',
                    'role.time',
                    'role.comment'
                ], [
                    'project_id' => $id,
                    'project.user_id' => $userId,
                    'role.table_id[!]' => $merges_id
                ]);
                // 返回作为普通用户的所有申购表
                $res1 = $this->container['db']->select($this->roleApplyTable, '*', [
                    'project_id' => $id,
                    'user_id' => $userId,
                    'table_id[!]' => $merges_id
                ]);
                foreach ($res1 as $key => $value) 
                {
                    array_push($res, $value);
                }
                $res = $this->tableMerge($res);
                return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
            }
            else
            {
                $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
                    '[><]'.$this->projectTable.'(project)' => 'project_id'
                ], [
                    'role.table_id',
                    'role.sum_money',
                    'role.man_phone',
                    'role.expense',
                    'role.dep_audit',
                    'role.center_audit',
                    'role.status',
                    'role.time',
                    'role.comment'
                ], [
                    'project_id' => $id,
                    'project.user_id' => $userId,
                ]);
                // 返回作为普通用户的所有申购表
                $res1 = $this->container['db']->select($this->roleApplyTable, '*', [
                    'project_id' => $id,
                    'user_id' => $userId,
                ]);
                foreach ($res1 as $key => $value) 
                {
                    array_push($res, $value);
                }
                $res = $this->tableMerge($res);
                return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
            }
                
        }
        else 
        {
            return self::jsonFail('请输入id');
        }
    }

    /**
     *  返回状态为0的申购表
     */
    public function mTablesList()
    {
        $this->checkAccess($this->getUserId(), '2');   
        $user_id = $this->getUserId(); 
        $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
            '[><]'.$this->projectTable.'(project)' => [
                'project_id'
            ]
        ] ,[
                'role.table_id',
                'role.sum_money',
                'role.man_phone',
                'role.expense',
                'role.dep_audit',
                'role.center_audit',
                'role.status',
                'role.time',
                'role.comment',
                'project.project_id',
                'project.name',
                'project.leader'
            ], [
                'role.status' => 0,
                'merge_id' => 0,
                'dep_audit_id' => $user_id
            ]);
            return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    /**
     *  返回状态为1的申购表
     */
    public function cTablesList()
    {
        $this->checkAccess($this->getUserId(), '3');  
        $user_id = $this->getUserId(); 
        $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
            '[><]'.$this->projectTable.'(project)' => [
                'project_id'
            ]
        ] ,[
                'role.table_id',
                'role.project_id',
                'role.sum_money',
                'role.man_phone',
                'role.expense',
                'role.dep_audit',
                'role.center_audit',
                'role.status',
                'role.time',
                'role.comment',
                'project.project_id',
                'project.name',
                'project.leader'                
            ], [
                'role.status' => 1,
                'merge_id' => 0,
                'center_audit_id' => $user_id
            ]);
            return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    /**
     *  返回状态为3的申购表
     */
    public function wTablesList()
    {
        $this->checkAccess($this->getUserId(), '4');        
        $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
            '[><]'.$this->projectTable.'(project)' => [
                'project_id'
            ]
        ] ,[
                'role.table_id',
                'role.sum_money',
                'role.man_phone',
                'role.expense',
                'role.dep_audit',
                'role.center_audit',
                'role.status',
                'role.time',
                'role.comment',
                'project.project_id',
                'project.name',
                'project.leader'                
            ], [
                'role.status' => 3,
                'merge_id' => 0
            ]);
            return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }
    /**
     *  返回状态为5的申购表
     */
    public function fTablesList()
    {
        $this->checkAccess($this->getUserId(), '4');            
        $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
            '[><]'.$this->projectTable.'(project)' => [
                'project_id'
            ]
        ] ,[
                'role.table_id',
                'role.sum_money',
                'role.man_phone',
                'role.expense',
                'role.dep_audit',
                'role.center_audit',
                'role.status',
                'role.time',
                'role.comment',
                'project.project_id',
                'project.name',
                'project.user_id',
                'project.leader'                
            ], [
                'role.status' => 5,
                'role.merge_id' => 0
            ]);
            return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    /**
     *  返回状态为5的申购表 且属于访问者的申购表
     */
    public function dTablesList()
    {
        $this->checkAccess($this->getUserId(), '12345');                  
        $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
            '[><]'.$this->projectTable.'(project)' => [
                'project_id'
            ]
        ] ,[
                'role.table_id',
                'role.sum_money',
                'role.man_phone',
                'role.expense',
                'role.dep_audit',
                'role.center_audit',
                'role.status',
                'role.time',
                'role.comment',
                'project.project_id',
                'project.name',
                'project.user_id'
            ], [
                'role.status' => 5,
                'OR' => [
                    'project.user_id' => $this->getUserId(),
                    'role.user_id' => $this->getUserId()
                ]
            ]);
            $res = $this->tableMerge($res);
            return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    public function goodsList()
    {
        $this->checkAccess($this->getUserId(), '12345');                          
        $id = $_GET['table_id'];
        if($id)
        {
            $res = $this->container['db']->select($this->applyTable.'(apply)', [
                'apply.item_id',
                'apply.type',
                'apply.name',
                'apply.num',
                'apply.money',
                'apply.vender',
                'apply.time',
                'apply.for',
                'apply.place',
                'apply.store_type'
            ], [
                'table_id' => $id,
            ]);
        }
        else
        {
            return self::jsonFail('请输入id');
        }
        if(!$this->container['db']->error()[1])
        {
            return json_encode($res);
        }
        else
        {
            return self::jsonFail('获取失败');
        }
    }


    public function newApply()
    {
        $this->checkAccess($this->getUserId(), '12345');                                  
        $data = json_decode(file_get_contents("php://input"));
        $data = self::object_array($data);
        $details = $data['applyTable']['details'];
        $common = $data['applyTable']['common'];
        $balance = $this->container['db']->select($this->projectTable, 'balance', [
            'project_id' => $common['project_id']
        ])[0];
        if(!$this->container['db']->error()[1])
        {
            if($balance < $common['sum_money']) return self::jsonFail('申购表总金额大于项目余额');
        }
        else 
        {
            return self::jsonFail('新增失败');
        }
        $data['balance'] = $balance;
        if($common)
        {
            $res = $this->container['db']->action(function($database) use($data)
            {
                $details = $data['applyTable']['details'];
                $common = $data['applyTable']['common'];
                $user_id = $this->getUserId();
                $database->insert($this->roleApplyTable, [
                    'project_id' => $common['project_id'],
                    'sum_money' => $common['sum_money'],
                    'man_phone' => $common['man_phone'],
                    'expense' => $common['expense'],
                    'dep_audit' => $common['dep_audit'],
                    'center_audit' => $common['center_audit'],
                    'user_id' => $user_id,
                    'dep_audit_id' => $common['dep_audit_id'],
                    'center_audit_id' => $common['center_audit_id'],
                    'time' => time()
                ]);
                if($database->id())
                {
                    $id = $database->id();
                    foreach ($details as $key => $value) 
                    {
                        $row = $database->insert($this->applyTable, [
                            'table_id' => $id,
                            'item_id' => '',
                            'type' => $value['type'],
                            'name' => $value['name'],
                            'num' => $value['num'],
                            'money' => $value['money'],
                            'vender' => $value['vender'],
                            'time' => $value['time'],
                            'for' => $value['for'],
                            'place' => $value['place'],
                            'store_type' => $value['store_type']
                        ]);
                        if(!$row->rowCount())
                        {
                            return false;
                        }
                    }
                    $balance = $data['balance'] - $common['sum_money'];
                    $row1 = $database->update($this->projectTable, [
                        'balance' => $balance
                    ]);
                    return ($row1->rowCount())?(true):(false);
                    // return false;
                }
                else
                {
                    return false;
                }
            });
            if($res)
            {
                return self::jsonSuccess('提交成功');
            }
            else
            {
                return self::jsonFail('提交失败');
            }
        }
    }

    public function updateApply()
    {
        $this->checkAccess($this->getUserId(), '12345');                          
        $data = json_decode(file_get_contents("php://input"));
        $data = self::object_array($data);
        $details = $data['applyTable']['details'];
        $common = $data['applyTable']['common'];
        $table_id = $data['applyTable']['table_id'];
        if($table_id)
        {
            $res = $this->container['db']->action(function($database) use($data)
            {
                $details = $data['applyTable']['details'];
                $common = $data['applyTable']['common'];  
                $table_id = $data['applyTable']['table_id'];
                $status = $database->select($this->roleApplyTable, 'status',[
                    'table_id' => $table_id
                ])[0];
                if($status == 2)
                {
                    $sum_money = 0;
                    foreach ($details as $key => $value) 
                    {
                        $database->update($this->applyTable, [
                            'type' => $value['type'],
                            'name' => $value['name'],
                            'num' => $value['num'],
                            'money' => $value['money'],
                            'vender' => $value['vender'],
                            'time' => $value['time'],
                            'for' => $value['for'],
                            'place' => $value['place'],
                            'store_type' => $value['store_type']
                        ], [
                            'item_id' => $value['item_id'],
                            'table_id' => $table_id
                        ]);
                        $sum_money +=  intval($value['money']);
                        if($database->error()[1]) return false;
                    }
                    $database->update($this->roleApplyTable, [
                        'sum_money' => $sum_money,
                        'man_phone' => $common['man_phone'],
                        'expense' => $common['expense'],
                        'dep_audit' => $common['dep_audit'],
                        'center_audit' => $common['center_audit'],
                        'dep_audit_id' => $common['dep_audit_id'],
                        'center_audit_id' => $common['center_audit_id'],
                        'time' => time(),
                        'status' => 0
                    ], [
                        'table_id' => $table_id
                    ]);  
                    if($database->error()[1]) return false;
                    return true;
                }
                else if($status == 4) 
                {
                    $sum_money = 0;
                    foreach ($details as $key => $value) 
                    {
                        $database->update($this->applyTable, [
                            'type' => $value['type'],
                            'name' => $value['name'],
                            'num' => $value['num'],
                            'money' => $value['money'],
                            'vender' => $value['vender'],
                            'time' => $value['time'],
                            'for' => $value['for'],
                            'place' => $value['place'],
                            'store_type' => $value['store_type']
                        ], [
                            'table_id' => $table_id,
                            'item_id' => $value['item_id']
                        ]);
                        $sum_money += intval($value['money']);
                        if($database->error()[1]) return false;
                    }
                    $database->update($this->roleApplyTable, [
                        'sum_money' => $sum_money,
                        'man_phone' => $common['man_phone'],
                        'expense' => $common['expense'],
                        'dep_audit' => $common['dep_audit'],
                        'center_audit' => $common['center_audit'],
                        'dep_audit_id' => $common['dep_audit_id'],
                        'center_audit_id' => $common['center_audit_id'],
                        'time' => time(),
                        'status' => 1 
                    ], [
                        'table_id' => $table_id
                    ]);
                    if($database->error()[1]) return false;
                    return true;
                }
                else
                {
                    return false;
                }
                
            });
            if($res)
            {
                return self::jsonSuccess('更新成功');
            }
            else
            {
                return self::jsonFail('更新失败');
            }
        }
        else
        {
            return self::jsonFail('请输入表id');
        }
    }

    public function projectDel()
    {
        $this->checkAccess($this->getUserId(), '1');                          
        if($_POST['id'])
        {
            $data = $this->container['db']->delete($this->projectTable, [
                'project_id' => $_POST['id']
            ]);
            return ($data->rowCount())?self::jsonSuccess('删除成功'):self::jsonFail('删除失败');
        }
        else 
        {
            return self::jsonFail('请输入id');
        }
    }

    public function tableDel()
    {
        $this->checkAccess($this->getUserId(), '12345');                          
        if($_POST['id'])
        {
            $res = $this->container['db']->action(function($database)
            {
                $data = $database->delete($this->roleApplyTable, [
                    'table_id' => $_POST['id'],
                    'status[!]' => [1, 3, 5]
                ]);
                if($data->rowCount())
                {
                    $data1 = $database->delete($this->applyTable, [
                        'table_id' => $_POST['id']
                    ]);
                    if(!$database->error()[1])
                    {
                        return true;
                    }
                    else 
                    {
                        return false;
                    }
                }
                else 
                {
                    return false;
                }
            });
            return ($res)?self::jsonSuccess('删除成功'):self::jsonFail('删除失败');
        }
        else 
        {
            return self::jsonFail('请输入申购表id');
        }
    }


    public function goodAdd()
    {
        $this->checkAccess($this->getUserId(), '12345');                          
        $data = json_decode(file_get_contents('php://input'));
        $data = self::object_array($data);
        if($data['applyItemList']['table_id'])
        {
            $status = $this->container['db']->select($this->roleApplyTable, 'status', [
                'table_id' => $data['applyItemList']['table_id'],
                'status' => ["1", "3", "5"]
            ]);
            // var_dump($this->container['db']->log());
            if($status) return self::jsonFail('非待审核申购表不能更改');
            $res = $this->container['db']->action(function($database) use($data) 
            {
                $table_id = $data['applyItemList']['table_id'];
                $details = $data['applyItemList']['details'];
                foreach ($details as $key => $value) 
                {
                    # code...
                    $row = $database->insert($this->applyTable, [
                        'type' => $value['type'],
                        'name' => $value['name'],
                        'num' => $value['num'],
                        'money' => $value['money'],
                        'vender' => $value['vender'],
                        'time' => $value['time'],
                        'for' => $value['for'],
                        'place' => $value['place'],
                        'store_type' => $value['store_type'],
                        'table_id' => $table_id,
                        'item_id' => ''
                    ]);
                    if(!$row->rowCount()) return false;
                }
                return true;
            });
            if($res)
            {
                return self::jsonSuccess('增加成功');
            }
            else
            {
                return self::jsonFail('增加失败');
            }
        }   
        else 
        {
            return self::jsonFail('请输入表id');
        }     
    }
    
    public function goodsDel()
    {
        $this->checkAccess($this->getUserId(), '12345');                          
        if($_POST['item_id'])
        {
            $res = $this->container['db']->select($this->applyTable.'(apply)', [
               '[><]'.$this->roleApplyTable.'(role)' => 'table_id'
            ], [
                'role.table_id'
            ], [
                'apply.item_id' => $_POST['item_id'],
                'status' => ["1", "3", "5"],
            ]);
            if($res) return self::jsonFail('非待审核申购表不能更改');
            $data = $this->container['db']->delete($this->applyTable, [
                'item_id' => $_POST['item_id']
            ]);
            return ($data->rowCount())?self::jsonSuccess('删除成功'):self::jsonFail('删除失败');
        }
        else
        {
            return self::jsonFail('请输入物品序号');
        }
    }

    
    public function mTableCheck()
    {
        $this->checkAccess($this->getUserId(), '2');                                  
        if($_POST['table_id'])
        {
            $tables_id = $this->container['db']->select($this->roleApplyTable, 'table_id', [
                'merge_id' => $_POST['table_id']
            ]);
            if($tables_id)
            {
                if($_POST['action'] == 0)
                {
                    // 是merge表 删除表， 更新原表的merge_id = 0 和status = 2
                    $actStatus = $this->container['db']->action(function($database) use($tables_id) 
                    {
                        foreach ($tables_id as $key => $table_id) 
                        {
                            @$res1 = $database->update($this->roleApplyTable, [
                                'status' => 2,
                                'comment' => $_POST['comment'],
                                'merge_id' => 0
                            ], [
                                'table_id' => $table_id
                            ]);
                            if(!$res1->rowCount()) return false;
                            // 更新物品状态
                            $res2 = $this->container['db']->update($this->applyTable, [
                                'is_merge' => 0
                            ], [
                                'table_id' => $table_id
                            ]);
                            if(!$res2->rowCount()) return false;
                            $user_id = $this->getUserId();
                            $res3 = $this->checkRecord($user_id, $table_id, 0);
                            if(!$res3) return false;
                        }
                        // 删除合并申购表
                        $res3 = $database->delete($this->roleApplyTable, [
                            'table_id' => $_POST['table_id']
                        ]);
                        // 申购合并物品
                        if(!$res3->rowCount()) return false;
                        $res4 = $database->delete($this->applyTable, [
                            'table_id' => $_POST['table_id']
                        ]);
                        if(!$res4->rowCount()) return false;
                        return true;
                    });
                    return ($actStatus)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));
                }
                else if($_POST['action'] == 1)
                {
                    $actStatus = $this->container['db']->action(function($database) use($tables_id) 
                    {
                        foreach ($tables_id as $key => $table_id) 
                        {
                            $res = $database->update($this->roleApplyTable, [
                                'status' => 1
                            ], [
                                'table_id' => $table_id
                            ]);
                        }
                        if(!$res->rowCount()) return false;
                        $res1 = $database->update($this->roleApplyTable, [
                            'status' => 1
                        ], [
                            'table_id' => $_POST['table_id']
                        ]);
                        if(!$res1->rowCount()) return false;
                        $user_id = $this->getUserId();
                        $res2 = $this->checkRecord($user_id, $_POST['table_id'], 1);
                        if(!$res2) return false;
                        return true;
                    });
                    return ($actStatus)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));
                }
                else
                {
                    return self::jsonFail('审核失败');  
                }
            }
            else 
            {
                if($_POST['action'] == 0)
                {
                    @$res = $this->container['db']->update($this->roleApplyTable, [
                        'status' => 2,
                        'comment' => $_POST['comment']
                    ], [
                        'table_id' => $_POST['table_id']
                    ]);
                    if(!$res->rowCount()) return self::jsonFail('审核失败');
                    $user_id = $this->getUserId();
                    $res2 = $this->checkRecord($user_id, $_POST['table_id'], 0);
                    return ($res2)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));
                }
                else if($_POST['action'] == 1)
                {
                    $res = $this->container['db']->update($this->roleApplyTable, [
                        'status' => 1
                    ], [
                        'table_id' => $_POST['table_id']
                    ]);
                    if(!$res->rowCount()) return self::jsonFail('审核失败');
                    $user_id = $this->getUserId();
                    $res2 = $this->checkRecord($user_id, $_POST['table_id'], 1);
                    return ($res2)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));
                }
                else
                {
                    return self::jsonFail('审核失败');  
                }
            }
        }
        else 
        {
            return self::jsonFail('请输入表id');
        }
    }

    public function cTableCheck()
    {
        $this->checkAccess($this->getUserId(), '3');       
        // 是merge表 删除表， 更新原表的merge_id = 0 和status = 4    
        if($_POST['table_id'])
        {
            $tables_id = $this->container['db']->select($this->roleApplyTable, 'table_id', [
                'merge_id' => $_POST['table_id']
            ]);
            if($tables_id)
            {
                if($_POST['action'] == 0)
                {
                    // 是merge表 删除表， 更新原表的merge_id = 0 和status = 2
                    $actStatus = $this->container['db']->action(function($database) use($tables_id) 
                    {
                        foreach ($tables_id as $key => $table_id) 
                        {
                            @$res1 = $database->update($this->roleApplyTable, [
                                'status' => 4,
                                'comment' => $_POST['comment'],
                                'merge_id' => 0
                            ], [
                                'table_id' => $table_id
                            ]);
                            if(!$res1->rowCount()) return false;
                            $res2 = $this->container['db']->update($this->applyTable, [
                                'is_merge' => 0
                            ], [
                                'table_id' => $table_id
                            ]);
                            if(!$res2->rowCount()) return false;
                            $user_id = $this->getUserId();
                            $res5 = $this->checkRecord($user_id, $table_id, 0);
                            if(!$res5) return false;
                        }
                        $res3 = $database->delete($this->roleApplyTable, [
                            'table_id' => $_POST['table_id']
                        ]);
                        if(!$res3->rowCount()) return false;
                        $res4 = $database->delete($this->applyTable, [
                            'table_id' => $_POST['table_id']
                        ]);
                        if(!$res4->rowCount()) return false;
                        return true;
                    });
                    return ($actStatus)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));
                }
                else if($_POST['action'] == 1)
                {
                    $actStatus = $this->container['db']->action(function($database) use($tables_id) 
                    {
                        foreach ($tables_id as $key => $table_id) 
                        {
                            $res = $database->update($this->roleApplyTable, [
                                'status' => 3
                            ], [
                                'table_id' => $table_id
                            ]);
                            if(!$res->rowCount()) return false;
                        }
                        $res1 = $database->update($this->roleApplyTable, [
                            'status' => 3
                        ], [
                            'table_id' => $_POST['table_id']
                        ]);
                        if(!$res1->rowCount()) return false;
                        return true;
                        $user_id = $this->getUserId();
                        $res2 = $this->checkRecord($user_id, $_POST['table_id'], 1);
                        if(!$res2) return false;
                    });
                    return ($actStatus)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));
                }
                else
                {
                    return self::jsonFail('审核失败');  
                }
            }
            else 
            {
                if($_POST['action'] == 0)
                {
                    $res = $this->container['db']->update($this->roleApplyTable, [
                        'status' => 4,
                        'comment' => $_POST['comment']
                    ], [
                        'table_id' => $_POST['table_id']
                    ]);
                    if(!$res->rowCount()) return self::jsonFail('审核失败');
                    $user_id = $this->getUserId();
                    $res2 = $this->checkRecord($user_id, $_POST['table_id'], 0);
                    return ($res2)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));
                }
                else if($_POST['action'] == 1)
                {
                    $res = $this->container['db']->update($this->roleApplyTable, [
                        'status' => 3
                    ], [
                        'table_id' => $_POST['table_id']
                    ]);
                    if(!$res->rowCount()) return self::jsonFail('审核失败');
                    $user_id = $this->getUserId();
                    $res2 = $this->checkRecord($user_id, $_POST['table_id'], 1);
                    return ($res2)?(self::jsonSuccess('审核成功')):(self::jsonFail('审核失败'));;
                }
                else
                {
                    return self::jsonFail('审核失败');  
                }
            }
        }
        else 
        {
            return self::jsonFail('请输入表id');
        }
    }


    public function details()
    {
        $this->checkAccess($this->getUserId(), '12345');                                  
        if(isset($_GET['project_id']))
        {
            $res = $this->container['db']->select($this->projectTable, '*', [
                'project_id' => $_GET['project_id']
            ]);
            return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
        }
        else if(isset($_GET['table_id']))
        {
            $res = $this->container['db']->select($this->roleApplyTable.'(role)', [
                '[><]'.$this->projectTable.'(project)' => 'project_id'
            ], [
                'project.leader',
                'role.table_id',
                'role.status',
                'role.project_id',
                'project.name',
                'role.sum_money',
                'role.man_phone',
                'role.expense',
                'role.dep_audit',
                'role.center_audit'
            ], [
                'table_id' => $_GET['table_id']
            ]);
            return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
        }
        else
        { 
            return self::jsonFail('获取失败');
        }
    }

    // 项目负责人查看人员列表
    public function pUserList()
    {
        $this->checkAccess($this->getUserId(), '1');                                  
        $res = $this->container['db']->select($this->userTable, [
            'id',
            'username'
        ]);
        return ($this->container['db']->error()[1])?(self::jsonFail('数据库错误')):(json_encode($res));
    }

    public function pUserUpdate()
    {
        $this->checkAccess($this->getUserId(), '1');  
        $data = json_decode(file_get_contents("php://input"));
        $data = self::object_array($data);  
        $data = $data['userAdd'];
        if($data['user_id'] && $data['project_id'])
        {
            //  用于判断属于该id的项目
            $userId = $this->getUserId();
            $sql = 'delete role from '.$this->roleProjectTable.' as role, '.$this->projectTable.' as project where role.project_id = '.$this->container['db']->quote($data['project_id']).' and project.project_id = '.$this->container['db']->quote($data['project_id']).' and project.user_id = '.$this->container['db']->quote($userId); 
            $this->container['db']->query($sql);
            // echo $this->container['db']->rowCount();
            foreach ($data['user_id'] as $key => $value) 
            {
                $dataRes = $this->container['db']->insert($this->roleProjectTable, [
                    'user_id' => $value,
                    'project_id' => $data['project_id']
                ]);
                if($this->container['db']->error()[1]) return self::jsonFail('数据库错误');
                if(!$dataRes->rowCount()) return self::jsonFail('修改失败');
            }   
            return self::jsonSuccess('修改成功');
        }
        else 
        {
            return self::jsonFail('请输入user_id和project_id');
        }
    }

    public function aUserList()
    {
        $this->checkAccess($this->getUserId(), '1'); 
        $id = $this->getUserId(); 
        if($_GET['project_id'])
        {
            $res = $this->container['db']->select($this->roleProjectTable.'(role)', [
                '[><]'.$this->userTable.'(user)' => [
                    'role.user_id' => 'id',
                    
                ],
                '[><]'.$this->projectTable.'(project)' => 'project_id'
            ], [
                'user.id',
                'user.username'
            ], [
                'role.project_id' => $_GET['project_id'],
                'project.user_id' => $id
            ]);
            return ($this->container['db']->error()[1])?(self::jsonFail('数据库出错')):(json_encode($res));
        }        
        else 
        {
            return self::jsonFail('请输入project_id');
        }
    }

    public function tablesCombine()
    {
        $this->checkAccess($this->getUserId(), '2'); 
        $data = json_decode(file_get_contents("php://input"));
        $data = self::object_array($data);
        $tables = $data['tables'];
        // var_dump($tables);
        $resStatus = $this->container['db']->action(function($database) use($tables) 
        {
            $resTables = array();
            // var_dump($tables);
            for($i = 0; $i < count($tables); $i++)
            {
                $table_id = $tables[$i]['table_id'];
                if($table_id)
                {
                    // 取出要合并的表的数据
                    $resTables[$table_id] = $database->select($this->roleApplyTable, '*', [
                        'table_id' =>$table_id,
                        'status' => 0
                    ])[0];
                    if($database->error()[1]) return false;
                    for($j = 0; $j < count($tables[$i]['item_id']); $j++)
                    {
                        if($tables[$i]['item_id'][$j])
                        {
                                // 取出要合并的物品数据
                                $resTables[$table_id]['item_merge'][] = $database->select($this->applyTable, '*', [
                                    'item_id' => $tables[$i]['item_id'][$j],
                                    'table_id' => $tables[$i]['table_id']
                                ])[0];
                                if($database->error()[1]) return false;
                                // 更新物品merge状态
                                $data = $database->update($this->applyTable, [
                                    'is_merge' => '1',
                                ], [
                                    'item_id' => $tables[$i]['item_id'][$j]
                                ]);
                                if(!$data->rowCount()) return false;
                        }
                        else 
                        {
                            return false;
                        }
                    }
                    // 取出不需要合并的物品
                    $resTables[$table_id]['item'] = $database->select($this->applyTable, '*', [
                        'table_id' => $tables[$i]['table_id'],
                        'is_merge' => '0' 
                    ]);
                    if($database->error()[1]) return false;
                }
                else 
                {
                    return false;
                }
            }
            // var_dump($tables);
            // var_dump($resTables);
            // var_dump($resTables['49']);
            // var_dump($resTables['49']['item_merge']);
            // var_dump($resTables['49']['item']);
            $sum_money = 0;
            $sum_num = 0;
            foreach ($resTables as $key => $content) 
            {
                // 算表的总金额
                $sum_money += $content['sum_money'];
                for ($i=0; $i < count($content['item_merge']); $i++) 
                { 
                    // 算要合并的物品数量总和
                    $sum_num += $content['item_merge'][$i]['num'];
                }
            }
            // $resTables[$tables[0]['table_id']]['sum_money'] = $sum_money;
            // $resTables[$tables[0]['table_id']]['man_phone'] = $this->getUserPhone();
            // $resTables[$tables[0]['table_id']]['item'][0]['num'] = $sum_num;
            // var_dump($resTables['48']);
            // 插入新表
            $database->insert($this->roleApplyTable, [
                'table_id' => '',
                'project_id' =>  $resTables[$tables[0]['table_id']]['project_id'],
                'sum_money' =>  $sum_money,
                'man_phone' => $this->getUsername().' '.$this->getUserPhone(),
                'expense' => $resTables[$tables[0]['table_id']]['expense'],
                'dep_audit' => $resTables[$tables[0]['table_id']]['dep_audit'],
                'center_audit' => $resTables[$tables[0]['table_id']]['center_audit'],
                'user_id' => $this->getUserId(),
                'status' => '0',
                'time' => time(),
                'merge_id' => '0'
            ]);
            $new_table_id = $database->id();
            if(!$new_table_id) return false;
            foreach ($resTables as $key => $value) 
            {
                // 更新旧表状态
                $data1 = $database->update($this->roleApplyTable, [
                    'merge_id' => $new_table_id
                ], [
                    'table_id' => $key
                ]);
                if(!$data1->rowCount()) return false;
            }
            // 插入合并后的物品
            $data2 = $database->insert($this->applyTable, [
                'item_id' => '',
                'table_id' => $new_table_id,
                'name' => $resTables[$tables[0]['table_id']]['item_merge'][0]['name'],
                'type' => $resTables[$tables[0]['table_id']]['item_merge'][0]['type'],
                'num' => $sum_num,
                'money' => $resTables[$tables[0]['table_id']]['item_merge'][0]['money'],
                'vender' => $resTables[$tables[0]['table_id']]['item_merge'][0]['vender'],
                'time' => $resTables[$tables[0]['table_id']]['item_merge'][0]['time'],
                'for' => $resTables[$tables[0]['table_id']]['item_merge'][0]['for'],
                'place' => $resTables[$tables[0]['table_id']]['item_merge'][0]['place'],
                'store_type' => $resTables[$tables[0]['table_id']]['item_merge'][0]['store_type'],
                'is_merge' => '0'
            ]);
            if(!$data2->rowCount()) return false;
            // 插入不需要合并的物品
            foreach ($resTables as $key => $value) 
            {
                for($i = 0; $i < count($value['item']); $i ++)
                {
                    $data3 = $database->insert($this->applyTable, [
                        'item_id' => '',
                        'table_id' => $new_table_id,
                        'name' => $resTables[$key]['item'][$i]['name'],
                        'type' => $resTables[$key]['item'][$i]['type'],
                        'num' => $resTables[$key]['item'][$i]['num'],
                        'money' => $resTables[$key]['item'][$i]['money'],
                        'vender' => $resTables[$key]['item'][$i]['vender'],
                        'time' => $resTables[$key]['item'][$i]['time'],
                        'for' => $resTables[$key]['item_merge'][$i]['for'],
                        'place' => $resTables[$key]['item_merge'][$i]['place'],
                        'store_type' => $resTables[$key]['item_merge'][$i]['store_type'],
                        'is_merge' => '0'
                    ]);
                    if(!$data2->rowCount()) return false;
                }
            }
            return true;
        });
        return ($resStatus)?(self::jsonSuccess('合并成功')):(self::jsonFail('合并失败'));
    }

    public function checkList()
    {
        $user_id = $this->getUserId();
        $this->checkAccess($user_id, '23');
        return ($this->getCheckTable($user_id))?(json_encode($this->getCheckTable($user_id))):(self::jsonFail("获取失败"));
    }

    public function getCheckTable($user_id)
    {
        $res = $this->container['db']->select($this->checkTable.'(check)', [
            '[><]'.$this->roleApplyTable.'(role)' => 'table_id'
        ], [
            'check.check_id',
            'check.table_id',
            'check.action',
            'check.time',
            'role.project_id',
            'role.sum_money',
            'role.man_phone',
            'role.expense',
            'role.dep_audit',
            'role.center_audit',
            'role.comment'
        ], [
            'check.user_id' => $user_id
        ]);
        return ($this->container['db']->error()[1])?(false):($res);
    }

}